<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          style="margin-left: 820px;"
          v-hasPermi="['system:standard:add']"
        >新增薪资标准</el-button>
        
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:standard:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:standard:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:standard:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:standard:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->







    <!-- <el-table v-loading="loading" :data="standardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="基本工资" align="center" prop="baseSalary" />
      <el-table-column label="岗位津贴" align="center" prop="allowance" />
      <el-table-column label="绩效奖金" align="center" prop="performanceBonus" />
      <el-table-column label="加班费" align="center" prop="overtimePay" />
      <el-table-column label="扣款" align="center" prop="deductionId">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDeduction(scope.row.deductionId)"
          >查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="个人所得税" align="center" prop="tax" />
      <el-table-column label="总薪资" align="center" prop="totalSalary" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:standard:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:standard:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    <el-card class="standard-card" v-for="item in standardList" :key="item.id" style="margin-bottom: 12px;"  shadow="hover">
      <el-descriptions :title="item.name" :bordered="true" size="small" column="3">
        <el-descriptions-item label="姓名">{{ item.userName }} ( {{ item.deptName }} ) </el-descriptions-item>
        <el-descriptions-item label="基本工资">{{ item.baseSalary }}</el-descriptions-item>
        <el-descriptions-item label="岗位津贴">{{ item.allowance }}</el-descriptions-item>
        <el-descriptions-item label="绩效奖金">{{ item.performanceBonus }}</el-descriptions-item>
        <el-descriptions-item label="加班费">{{ item.overtimePay }}</el-descriptions-item>
        <el-descriptions-item label="扣款">
          <!-- <el-button size="mini" type="text" @click="handleDeduction(item.id)">查看</el-button> -->
          {{ item.salaryReductionList.map(item => `${item.name}: ${item.money}`).join('; ') }}
        </el-descriptions-item>
        <el-descriptions-item label="个人所得税">{{ item.tax }}</el-descriptions-item>
        <el-descriptions-item label="总薪资">{{ item.totalSalary }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ item.remark }}</el-descriptions-item>
      </el-descriptions>
      <div class="button-group">
        <el-button size="mini" type="text" icon="el-icon-top-right" @click="handleToSend(item)" v-hasPermi="['system:standard:edit']">发薪</el-button>
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(item)" v-hasPermi="['system:standard:edit']">变更</el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(item)" v-hasPermi="['system:standard:remove']">删除</el-button>
      </div>
    </el-card>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改薪资标准对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="用户">
          <el-select v-model="form.userId" placeholder="请选择">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input v-model="form.baseSalary" placeholder="请输入基本工资" />
        </el-form-item>
        <el-form-item label="岗位津贴" prop="allowance">
          <el-input v-model="form.allowance" placeholder="请输入岗位津贴" />
        </el-form-item>
        <el-form-item label="绩效奖金" prop="performanceBonus">
          <el-input v-model="form.performanceBonus" placeholder="请输入绩效奖金" />
        </el-form-item>
        <el-form-item label="加班费" prop="overtimePay">
          <el-input v-model="form.overtimePay" placeholder="请输入加班费" />
        </el-form-item>
        <!-- <el-form-item label="所得税" prop="tax">
          <el-input v-model="form.tax" placeholder="请输入个人所得税" />
        </el-form-item> -->
        <!-- <el-form-item label="总薪资" prop="totalSalary">
          <el-input v-model="form.totalSalary" placeholder="请输入总薪资" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">扣款管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSalaryReduction">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSalaryReduction">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="salaryReductionList" :row-class-name="rowSalaryReductionIndex" width="700px" @selection-change="handleSalaryReductionSelectionChange" ref="salaryReduction">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="扣款名称" prop="name" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" placeholder="请选择扣款名称">
                <el-option
                  v-for="dict in dict.type.sys_salary_reductions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="扣款总额" prop="money" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.money" placeholder="请输入扣款总额" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStandard, getStandard, delStandard, addStandard, updateStandard, getReductionList,getUserList } from "@/api/system/standard";
import {  addSalaryRecord } from "@/api/system/salaryRecord";
export default {
  name: "Standard",
  dicts: ['sys_salary_reductions'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSalaryReduction: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 薪资标准表格数据
      standardList: [],
      // 扣款管理表格数据
      salaryReductionList: [],
      // 每项扣款列表
      reductionList: [],
      // 选择用户数据
      users: [],
      // 弹出层标题
      title: "",
      // 发薪资弹出框
      sendOpen: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        baseSalary: null,
        allowance: null,
        performanceBonus: null,
        overtimePay: null,
        deductionId: null,
        tax: null,
        totalSalary: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      sendForm: {
        userId: null,
        userName: null,
        money: null
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  computed: {
    formattedReductionList(salaryReductionList) {
    if (Array.isArray(salaryReductionList)) {
      return salaryReductionList.map(item => `${item.name}: ${item.money}`).join('; ');
    } else {
      return '无扣款信息';
    }
  }
  },
  methods: {
    /** 查询薪资标准列表 */
    getList() {
      this.loading = true;
      listStandard(this.queryParams).then(response => {
        this.standardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList() {
      getUserList().then(response => {
          this.users = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        userId: null,
        userName: null,
        // deptId: null,
        deptName: null,
        baseSalary: null,
        allowance: null,
        performanceBonus: null,
        overtimePay: null,
        deductionId: null,
        tax: null,
        totalSalary: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.salaryReductionList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加薪资标准";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStandard(id).then(response => {
        this.form = response.data;
        this.salaryReductionList = response.data.salaryReductionList;
        this.open = true;
        this.title = "修改薪资标准";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          // 计算总薪资
          let totalSalary = parseFloat(this.form.baseSalary || 0) + parseFloat(this.form.allowance || 0) + 
                       parseFloat(this.form.performanceBonus || 0) + parseFloat(this.form.overtimePay || 0);

          // 减去扣款中的数额
          if (Array.isArray(this.salaryReductionList)) {
            for (let reduction of this.salaryReductionList) {
              totalSalary -= parseFloat(reduction.money || 0);
            }
          }

              // 计算个人所得税
          let tax = this.calculateIncomeTax(totalSalary); // 假设 calculateIncomeTax 是计算个人所得税的方法

          // 将计算出的个人所得税数额从总薪资中减去
          totalSalary -= tax;

          // 将计算出的总薪资和个人所得税赋值给表单数据中的 totalSalary 和 tax 字段
          // this.form.totalSalary = totalSalary;
          this.form.tax = tax;

          // 将计算出的总薪资赋值给表单数据中的 totalSalary 字段
          this.form.totalSalary = totalSalary;
          this.form.salaryReductionList = this.salaryReductionList;

          
          if (this.form.id != null) {
            updateStandard(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStandard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除薪资标准编号为"' + ids + '"的数据项？').then(function() {
        return delStandard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 扣款管理序号 */
    rowSalaryReductionIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 扣款管理添加按钮操作 */
    handleAddSalaryReduction() {
      let obj = {};
      obj.name = "";
      obj.money = "";
      obj.remark = "";
      this.salaryReductionList.push(obj);
    },
    /** 扣款管理删除按钮操作 */
    handleDeleteSalaryReduction() {
      if (this.checkedSalaryReduction.length == 0) {
        this.$modal.msgError("请先选择要删除的扣款管理数据");
      } else {
        const salaryReductionList = this.salaryReductionList;
        const checkedSalaryReduction = this.checkedSalaryReduction;
        this.salaryReductionList = salaryReductionList.filter(function(item) {
          return checkedSalaryReduction.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSalaryReductionSelectionChange(selection) {
      this.checkedSalaryReduction = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/standard/export', {
        ...this.queryParams
      }, `standard_${new Date().getTime()}.xlsx`)
    },
    /** 弹出扣款弹窗 */
    handleDeduction(row){

    },
    getReduction(id){
      
          // 同步地获取扣款信息字符串
          const reductionList = getReductionList(id);
          let reductionString = '';
          for (let i = 0; i < reductionList.length; i++) {
            reductionString += reductionList[i].name + " : " + reductionList[i].money + ";";
          }
          return reductionString;
    },
    calculateIncomeTax(income) {
      let taxableIncome = income - 5000;
      let taxRate = 0;

      if (taxableIncome <= 3000) {
        taxRate = 0.03;
      } else if (taxableIncome <= 12000) {
        taxRate = 0.1;
      } else if (taxableIncome <= 25000) {
        taxRate = 0.2;
      } else if (taxableIncome <= 35000) {
        taxRate = 0.25;
      } else if (taxableIncome <= 55000) {
        taxRate = 0.3;
      } else if (taxableIncome <= 80000) {
        taxRate = 0.35;
      } else {
        taxRate = 0.45;
      }

      return taxableIncome * taxRate;
    },
    handleToSend(item){
      this.$confirm('是否确定发薪, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.sendForm.userId = item.userId;
          this.sendForm.userName = item.userName;
          this.sendForm.money = item.totalSalary;
          // this.sendForm.standardId = item.id
          addSalaryRecord(this.sendForm).then(response => {
              this.$modal.msgSuccess("成功发薪");

          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      }
    
  }
};
</script>


<style scoped>
.button-group {
  display: flex;
  justify-content: flex-end;
  padding: 0 20px 10px 0; /* 调整按钮与卡片右侧的间距 */
}
</style>